package eg
{

import eg.MathUtils;
import com.fit4as.fit.Exception;


public class HP35 {

    public var r : Array = [0,0,0,0];
    private var s : Number = 0;

    public function key(key : String) : void {
        if (numeric(key)) {
            push(parseFloat(key));
        }
        else if (key == "enter") {
            down();
        }
        else if (key == "+") {
            push(pop() + pop());
        }
        else if (key == "-") {
            var t : Number = pop();
            push(pop() - t);
        }
        else if (key == "*") {
            push(pop() * pop());
        }
        else if (key == "/") {
            var t1 : Number = pop();
            push(pop() / t1);
        }
        else if (key == "x^y") {
            push(Math.exp(Math.log(pop()) * pop()));
        }
        else if (key == "clx") {
            r[0] = 0;
        }
        else if (key == "clr") {
            r[0] = r[1] = r[2] = r[3] = 0;
        }
        else if (key == "chs") {
            r[0] = -r[0];
        }
        else if (key == "x<>y") {
            var t2 : Number = r[0];
            r[0] = r[1];
            r[1] = t2;
        }
        else if (key == "r!") {
            r[3] = pop();
        }
        else if (key == "sto") {
            s = r[0];
        }
        else if (key == "rcl") {
            push(s);
        }
        else if (key == "sqrt") {
            push(Math.sqrt(pop()));
        }
        else if (key == "ln") {
            push(Math.log(pop()));
        }
        else if (key == "sin") {
            push(Math.sin(MathUtils.toRadians(pop())));
        }
        else if (key == "cos") {
            push(Math.cos(MathUtils.toRadians(pop())));
        }
        else if (key == "tan") {
            push(Math.tan(MathUtils.toRadians(pop())));
        }
        else {
            throw new Exception("can't do key: " + key);
        }
    }

    private function numeric(key : String) : Boolean {
        return key.length >= 1 &&
               ( isDigit(key.charAt(0)) ||
                 (key.length >= 2 &&
                  (key.charAt(0) == '-' &&
                   isDigit(key.charAt(1)))));
    }

    private function isDigit(ch : String) : Boolean
    {
        return ch >= "0" && ch <= "9";
    }

    private function down() : void
    {
        for (var i : int = 3; i > 0; i--) {
            r[i] = r[i - 1];
        }
    }

    private function up() : void
    {
        for (var i : int = 0; i < 3; i++) {
            r[i] = r[i + 1];
        }
    }

    private function push(value : Number) : void {
        down();
        r[0] = value;
    }

    private function pop() : Number {
        var result : Number = r[ 0 ];
        up();
        return result;
    }

}
}